'''
一个文件多线程下载
有bug,只能下第一页的
'''
import requests
import threading
import os
import time
import random
import queue
from lxml import etree


class MulThreadDownload(threading.Thread):
    def __init__(self, url, startpos, endpos, fd):
        print("MulThreadDownload_init")
        threading.Thread.__init__(self)
        self.url = url
        self.startpos = startpos
        self.endpos = endpos
        self.fd = fd

    def downloadRange(self):
        print('downloadRange')
        randomUserAgent = getRandomUserAgent()
        headers = {
            'User-Agent': randomUserAgent,
            "Range": "bytes=%s-%s" % (self.startpos, self.endpos)
        }
        try:
            res = requests.get(self.url, headers=headers, timeout=(30, 30))
            self.fd.seek(self.startpos)
            self.fd.write(res.content)
            self.fd.flush()
            sleep()
        except Exception as e:
            print(e)
            res.close()
            sleep()
            self.downloadRange()
        finally:
            res.close()

    def run(self):
        self.downloadRange()


def download(url, saveDir, threadNum):
    print('download')
    fileName = url.split('/')[-1]  # name.扩展
    res_size = getResSize(url)
    file = saveDir+fileName
    # 线程相关初始化
    threading.BoundedSemaphore(threadNum)  # 信号量
    step = res_size // threadNum  # 文件分块
    mtd_list = []  # 线程列表
    start = 0  # 起始位置
    end = -1  # 结束位置

    if(isFileExit(file, res_size)):
        pass
    else:
        # 生成空白文件
        tempf = open(file, 'w')
        tempf.close()
        with open(file, 'rb+') as f:
            fileno = f.fileno()
            # 循环获取范围参数
            while end < res_size-1:  # 如果文件大小为11字节，那就是获取文件0-10的位置的数据。如果end = 10，说明数据已经获取完了。
                start = end + 1
                end = start+step-1
                if end > res_size:
                    end = res_size
                # 每部分生成文件对象
                dup = os.dup(fileno)  # 复制文件句柄
                fd = os.fdopen(dup, 'rb+', -1)  # -1使用系统自定义缓存
                try:
                    mtd = MulThreadDownload(url, start, end, fd)
                    mtd.start()
                    mtd_list.append(mtd)
                except Exception as e:
                    print(e)
            for t in mtd_list:
                t.join()
        print('%s下载完成' % fileName)
        sleep()


def getRandomUserAgent():
    print('getRandomUserAgent')
    MY_USER_AGENT = [
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
        "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
        "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
        "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
        "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
        "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
        "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
        "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
        "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
        "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
    ]
    list_len = len(MY_USER_AGENT)
    randomInt = random.randint(0, list_len-1)
    return MY_USER_AGENT[randomInt]


def isFileExit(path, res_size):
    '''
    path:xx/xx/xx.png
    res_size:服务端获取的字节大小
    '''
    print('isFileExit')
    fileName = path.split('/')[-1]
    try:
        size = os.path.getsize(path)
        if(res_size == size):
            print('%s 已下载\n' % fileName)
            return True
        else:
            print('%s 下载不完整,正在重新下载\n' % fileName)
            return False
    except FileNotFoundError:
        print('%s 未下载,开始下载\n' % fileName)
        return False


def getResSize(url):
    print('getResSize')
    res = requests.head(url)
    size = res.headers['Content-Length']
    return int(size)


def mkdir(path):
    folder = os.path.exists(path)
    if not folder:
        os.makedirs(path)
        print('目录 %s 创建成功' % (path))
    else:
        print('目录 %s 已存在' % (path))


def sleep():
    randomInt = random.randint(4, 7)  # 随机休眠
    print('休眠 %d s' % randomInt)
    time.sleep(randomInt)


def getHtml(url):
    '''
    返回lxml解析好的html
    '''
    print('getHtml')
    randomUserAgent = getRandomUserAgent()
    headers = {'User-Agent': randomUserAgent}
    try:
        res = requests.get(url, headers, timeout=(30, 30))
    except Exception as e:
        print(e)
        sleep()
        getHtml(url)
    html = etree.HTML(res.text)
    return html


def downloadByPage(id, saveDir, threadNum):
    print('downloadByPage')
    # 第二页地址,因为第一页没有pageSum
    url = 'https://wallhaven.cc/search?q=id%{}&page={}'
    urlPageTwo = url.format(id, 2)
    # lxml解析后的html
    html = getHtml(urlPageTwo)
    # 获取总页数的div
    node = html.xpath(
        "//header[@class='thumb-listing-page-header']/h2/text()")
    # 总页数
    pageSum = int(node[1].split('/')[-1])
    # for-1获取每页的preview图片的地址
    for page in range(1, pageSum+2):
        print('开始遍历第 %d 页' % page)
        urlPage = url.format(id, page)  # 每页的地址
        print(urlPage)
        html = getHtml(urlPage)
        urls = html.xpath("//a[@class='preview']/@href")  # 每页对应预览图的地址
        # for-2获取preview图片对应的大图地址
        for url in urls:
            html = getHtml(url)
            url_real = html.xpath("//img[@id='wallpaper']/@src")
            print(url_real[0])
            # download(url_real[0], saveDir, threadNum)


if __name__ == "__main__":
    saveDir = './download_img/'
    mkdir(saveDir)
    threadNum = 5

    id = '3A35412'
    downloadByPage(id, saveDir, threadNum)
    print('$$$$$$$$$$$下载结束$$$$$$$$$$$')
